package com.ke.jun.bg.petpackmvvm.base.activity

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import com.ke.jun.bg.petpackmvvm.base.viewmodel.BaseViewModel
import com.ke.jun.bg.petpackmvvm.ext.getVmClazz
import com.ke.jun.bg.petpackmvvm.network.manager.NetState
import com.ke.jun.bg.petpackmvvm.network.manager.NetworkStateManager


/**
 * 描述　: ViewModelActivity基类，把ViewModel注入进来了
 */
abstract class BaseVmActivity<VM : BaseViewModel> : AppCompatActivity() {

    /**
     * 是否需要使用DataBinding 供子类BaseVmDbActivity修改，用户请慎动
     */
    protected var isUserDb = false

    lateinit var mViewModel: VM

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (!isUserDb) {
            setContentView(layoutId())
        } else {
            initDataBind()
        }
        init(savedInstanceState)
    }

    private fun init(savedInstanceState: Bundle?) {
        mViewModel = createViewModel()
        registerUiChange()
        initView(savedInstanceState)
        createObserver()
        NetworkStateManager.instance.mNetworkStateCallback.observeInActivity(this) {
            onNetworkStateChanged(it)
        }
    }


    /**
     * 网络变化监听 子类重写
     */
     open   fun onNetworkStateChanged(it: NetState?) {

    }

    /**
     * 创建LiveData数据观察者
     */
    abstract fun createObserver()


    private fun registerUiChange() {
        mViewModel.loadingChange.showDialog.observeInActivity(this) {
            showLoading(it)
        }

        mViewModel.loadingChange.dismissDialog.observeInActivity(this) {
            dismissLoading()
        }
    }

    /**
     * 网络请求的弹出加载页面
     */
    abstract fun showLoading(message: String = "请求网络中...")
    abstract fun dismissLoading()

    /**
     * 创建vm对象
     */
    private fun createViewModel(): VM {
        return ViewModelProvider(this).get(getVmClazz(this))
    }

    /**
     * 供子类BaseVmDbActivity 初始化Databinding操作
     */
    open fun initDataBind() {

    }

    /**
     * 加载布局
     */
    abstract fun layoutId(): Int

    /**
     * 初始化Viwe
     */
    abstract fun initView(savedInstanceState: Bundle?)


    protected fun addLoadingObserve(vararg viewModels: BaseViewModel) {
        viewModels.forEach { viewModel ->
            viewModel.loadingChange.showDialog.observeInActivity(this) {
                showLoading(it)
            }

            viewModel.loadingChange.dismissDialog.observeInActivity(this) {
                dismissLoading()
            }

        }
    }



    fun userDataBinding(isUserDb: Boolean) {
        this.isUserDb = isUserDb
    }



}